import json
import re
import requests

cookie = "SESSION=f5bd5c7e-e875-44d3-ae22-006de0ba02f2; __pstsid__=1a52d455d287cb1bd1e2c4f03b6fd74a"  # 账号信息
turn = ""
requestId = ""
response = ""
lessonAssoc =190682   # 课程信息，课程号
#http://jwxt.jmu.edu.cn/student/for-std/course-select/4759/turn/1621/select
id1=4759
id2=1621

# add-predicate(包含课程信息）
def add_predicate(requestId):
    print("正在add-predicate...(其中包含课程信息）")
    url = " http://jwxt.jmu.edu.cn/student/ws/for-std/course-select/add-predicate"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.39",
        "Cookie": cookie,
        "Host": "jwxt.jmu.edu.cn",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Content-Length": "159",
        "Content-Type": "application/json",
        "Origin": "http://jwxt.jmu.edu.cn"
        # "Referer":f"http://jwxt.jmu.edu.cn/student/for-std/course-select/4759/turn/{turn}/select"
    }
    date = {"studentAssoc": id1,
            "courseSelectTurnAssoc": id2,
            "requestMiddleDtos": [
                {
                    "lessonAssoc": lessonAssoc,
                    "virtualCost": 0,
                    "scheduleGroupAssoc": None}
            ],
            "coursePackAssoc": None
            }
    date = json.dumps(date)
    # print(type(date))
    response = requests.post(url=url, headers=headers, data=date, verify=False)
    # print(type(response))
    print(response.content)
    # print(type(response.content))
    # print(response.status_code)
    requestId = (response.content)
    return requestId


# predicate-response
def predicate_response(response):
    print("正在predicate-response...")
    url = "http://jwxt.jmu.edu.cn/student/ws/for-std/course-select/predicate-response"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.30",
        "Cookie": cookie,
        "Host": "jwxt.jmu.edu.cn",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Content-Length": "61",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Origin": "http://jwxt.jmu.edu.cn",
        "Referer": f"http://jwxt.jmu.edu.cn/student/for-std/course-select/4759/turn/{turn}/select"
    }
    date = {
        "studentId": id1,
        "requestId": requestId
    }

    response = requests.post(url=url, headers=headers, data=date, verify=False)
    print(response.text)
    return response


# add-request
def add_request(requestId):
    print("正在add-request...（包含课程信息）")
    url = "http://jwxt.jmu.edu.cn/student/ws/for-std/course-select/add-request"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.30",
        "Cookie": cookie,
        "Host": "jwxt.jmu.edu.cn",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Content-Length": "136",
        "Content-Type": "application/json",
        "Origin": "http://jwxt.jmu.edu.cn",
        "Referer": f"http://jwxt.jmu.edu.cn/student/for-std/course-select/4759/turn/{turn}/select"
    }
    date = {"studentAssoc": id1, "courseSelectTurnAssoc": id2,
            "requestMiddleDtos": [{"lessonAssoc": lessonAssoc, "virtualCost": 0, "scheduleGroupAssoc": None}]}
    date = json.dumps(date)
    response = requests.post(url=url, headers=headers, data=date, verify=False)
    print(response.content)
    requestId = response.content
    return requestId


# add-drop-response
def add_drop_response():
    print("正在add-drop-response...")
    url = "http://jwxt.jmu.edu.cn/student/ws/for-std/course-select/add-drop-response"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.30",
        "Cookie": cookie,
        "Host": "jwxt.jmu.edu.cn",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Content-Length": "136",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Origin": "http://jwxt.jmu.edu.cn",
        "Referer": f"http://jwxt.jmu.edu.cn/student/for-std/course-select/4759/turn/{turn}/select"
    }
    date = {
        "studentId": id1,
        "requestId": requestId
    }

    response = requests.post(url=url, headers=headers, data=date, verify=False)
    print(response.text)
    result = response.text
    issuccess="false"
    try:
        tishi = re.compile(r'.*?,"text":"(?P<tishi>.*?)"}', re.S)
        tishi = re.search(tishi, result).group("tishi")
        print("选课结果提示:" + tishi)
    except Exception as cuowu:
        print("无提示！", cuowu)
    try:
        jieguo = re.compile(r'.*?,"success":(?P<issuccess>.*?),"', re.S)
        issuccess = re.search(jieguo, result).group("issuccess")
        print("选课结果：" + issuccess)
    except Exception as cuowu:
        print("无结果！", cuowu)
    return issuccess


if __name__ == '__main__':
    # 获取turnId
    issuccess = "false"
    while (issuccess == "false"):
        try:
            # add-predicate(包含课程信息）
            requestId = add_predicate(requestId)
            # predicate-response
            response = predicate_response(response)
            # add-request
            requestId = add_request(requestId)
            # add-drop-response
            issuccess=add_drop_response()
        except Exception:
            print("发生异常...")
